<template>
  <n-modal
    v-model:show="showDialog"
    preset="dialog"
    class="rounded-[24px]"
    title=""
    style="width: 600px"
    :closable="true"
    :show-icon="false"
    :close-on-esc="true"
    :mask-closable="true"
  >
    <div class="min-h-[100px]">
      <div class="text-[24px] font-[400] text-center mb-[16px]">
        {{ $t("title.上传图片") }}
      </div>
      <n-spin :show="loading">
        <n-upload
          directory-dnd
          :multiple="false"
          :show-file-list="false"
          :on-change="handleChange"
          accept="image/*"
        >
          <n-upload-dragger>
            <div style="margin-bottom: 12px">
              <!-- <n-icon size="48" :depth="3">
                <ImageOutline />
              </n-icon> -->

              <img class="w-[36px]" src="/images/icons/uploadImage.png" />
            </div>
            <n-text style="font-size: 16px"> {{ $t("tips.上传图片提示") }} </n-text>
          </n-upload-dragger>
        </n-upload>
      </n-spin>
    </div>
  </n-modal>
</template>

<script setup>
import { ref } from "vue";
import { ImageOutline } from "@vicons/ionicons5";
import { useRouter, useRoute } from "vue-router";
import { uploadImage } from "@/api/product";
import { Session } from "@/utils/storage";
import { getToken } from "@/utils/request";
import { imageToBase64 } from "@/utils/common";
import bus from "@/utils/mitt";
const showDialog = ref(false);
const loading = ref(false);
const route = useRoute();
const router = useRouter();
const show = () => {
  if (getToken()) {
    showDialog.value = true;
  } else {
    //未登录
    bus.emit("showLoginDialog", true);
  }
};
const handleChange = async ({ fileList }) => {
  const file = fileList[0]?.file;
  if (file && file instanceof Blob) {
    loading.value = true;
    let imageUrl = await imageToBase64(file, true);
    const { data } = await uploadImage({
      imageBase64: imageUrl,
    });
    loading.value = false;
    // let imageList = route.name == "imageSearch" ? Session.get("imageList") || [] : [];
    let imageList = [];
    let item = {
      id: data.data,
      url: imageUrl,
    };
    imageList.push(item);
    Session.set("imageList", imageList);
    if (route.name != "imageSearch") {
      router.push("/imageSearch");
    } else {
      //更新列表
      bus.emit("updateImageList", item);
    }
    showDialog.value = false;
  } else {
  }
};
defineExpose({ show });
</script>

<style lang="scss" scoped></style>
